package com.leyou.user.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.auth.utils.JwtUtils;
import com.leyou.common.constants.MQConstants.*;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.common.utils.RegexUtils;
import com.leyou.user.dto.UserDTO;
import com.leyou.user.entity.User;
import com.leyou.user.mapper.UserMapper;
import com.leyou.user.service.UserService;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;
import static com.leyou.common.constants.RedisConstant.USER_VARIFY_CODE;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Autowired
    private JwtUtils jwtUtils;

    /**
     * 用户注册
     * @param user 用户信息
     * @param code 验证码
     */
    @Override
    public void userRegister(User user, String code) {
        if (null == user) {
            throw new LyException(400, "请求参数有误");
        }

        String key = USER_VARIFY_CODE + user.getPhone();
        // 防止数据过期
//        redisTemplate.expire(key, -1, TimeUnit.SECONDS);
        String codeRedis = redisTemplate.opsForValue().get(key);
        if (StringUtils.isEmpty(code) || !redisTemplate.hasKey(key) || !code.equals(codeRedis)) {
            throw new LyException(400, "验证码请求有误");
        }
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        save(user);
    }


    /**
     * 发送短信验证码
     * @param phone 手机号
     */
    @Override
    public void sendVerifyCode(String phone) {
        if (!RegexUtils.isPhone(phone)) {
            throw new LyException(400, "请求参数有误");
        }

        HashMap<String, String> msg = new HashMap<>();
        msg.put("phone", phone);
        String code = RandomStringUtils.randomNumeric(6);
        msg.put("code", code);
        amqpTemplate.convertAndSend(ExchangeConstants.SMS_EXCHANGE_NAME, RoutingKeyConstants.VERIFY_CODE_KEY, msg);
        redisTemplate.opsForValue().set(USER_VARIFY_CODE + phone, code, 5, TimeUnit.MINUTES);
    }

    /**
     * 根据用户名和密码查询
     * @param username 用户名
     * @param password 密码
     * @return UserDTO
     */
    @Override
    public UserDTO queryUserByNameAndPass(String username, String password) {
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            throw new LyException(400, "请求参数有误");
        }
        User user = query().eq("username", username).one();
        if (null == user) {
            throw new LyException(400, "用户名错误");
        } else if (!passwordEncoder.matches(password, user.getPassword())) {
            throw new LyException(400, "密码错误");
        }
        return BeanHelper.copyProperties(user, UserDTO.class);
    }


    /**
     * 判断信息是否存在
     *
     * @param data 要校验的数据
     * @param type 数据的类型
     * @return 是否存在
     */
    @Override
    public Boolean checkExists(String data, Integer type) {
        if (StringUtils.isBlank(data)) {
            throw new LyException(400, "请求参数有误");
        }

        String colName = null;
        switch (type) {
            case 1:
                colName = "username";
                break;
            case 2:
                if (!RegexUtils.isPhone(data)) {
                    throw new LyException(400, "请求参数有误");
                }
                colName = "phone";
                break;
            default:
                throw new LyException(400, "请求参数有误");
        }

        return query().eq(colName, data).count() == 1;
    }

}
